console.log('for webpack3.x')
const fs = require('fs')
const path = require('path')
module.exports = class clearSetting {
    constructor(options){
        this.options = options
    }
    apply(compiler) {
        compiler.plugin('emit', (compilation,callback) => {
        // compiler.hooks.afterEmit.tapAsync('clearSetting', (compilation,callback) => {
            const { file,toClear,version } = this.options
            let body = JSON.stringify(fs.readFileSync(path.join(__dirname,file),'utf-8'));
            let reg = new RegExp(`${toClear}.*?\;`,"g")
            let to = `${toClear} = ${"'"+"'"};`
            if(version) {
              let idx = body.indexOf('})')
              console.log(idx)
              body = body.substring(0,idx) + `SITE_CONFIG.version='${version}';` + body.substring(idx)
            }
            // console.log('fileDependencies',compilation.fileDependencies)
            console.log('contextDependencies',compilation.contextDependencies)
            body = body.replace(reg,to);
            console.log('path',file.split('./')[1])
            compilation.assets[file.split('./')[1]] = {
                source: function(){
                    return JSON.parse(body)
                },
                size: function(){
                    return body.length
                }
            }
            callback()
        })
    }
}
